package com.tongyi.lizhishop.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperTextView;
import com.amap.api.maps.model.LatLng;
import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.StoreApi;
import com.tongyi.lizhishop.beans.BusinessBean;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.beans.StoreBean;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.PromptDialogUtils;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;

import static com.tongyi.lizhishop.R.id.detail_address;

public class AddressActivity extends BaseActivity {


    public static final int SUCCESS = 2;
    private static final int GETLATLNG = 10;
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.choose1)
    TextView choose1;
    @BindView(R.id.choose2)
    TextView choose2;
    @BindView(R.id.choose3)
    TextView choose3;
    @BindView(R.id.radioGrop)
    LinearLayout radioGrop;
    @BindView(R.id.lantie)
    SuperTextView lantie;
    @BindView(R.id.activity_address)
    LinearLayout activityAddress;
    ArrayList<BusinessBean.ArrayBean> options1Items = new ArrayList();
    ArrayList<BusinessBean.ArrayBean> options2Items = new ArrayList();
    ArrayList<BusinessBean.ArrayBean> options3Items = new ArrayList();
    @BindView(detail_address)
    EditText detailAddress;
    @BindView(R.id.confirm)
    Button confirm;
    private int options1Index = -1;
    private int options2Index = -1;
    private int options3Index = -1;
    private PromptDialog prompDialog;
    private String longa = "";//经度
    private String lati = "";//维度
    private LatLng resultLatlng;
    private boolean isSubmit = false;
    private String sel_busid1;
    private String sel_busid2;
    private String sel_busid3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        ButterKnife.bind(this);
        initTitleBarView(titlebar, "地区地址");
        prompDialog = PromptDialogUtils.getPrompDialog(this);
        initView();
        loadData();
    }

    private void loadData() {
        APIServiceManager.getInstance().create(StoreApi.class)
                .infoSeller(SPUtils.getInstance().getString("userid"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<StoreBean>() {
                    @Override
                    public void onSuccess(StoreBean value) {
                        prompDialog.dismissImmediately();
                        choose1.setText(value.getArray().getBusname1());
                        choose2.setText(value.getArray().getBusname2());
                        choose3.setText(value.getArray().getBusname3());
                        sel_busid1 = value.getArray().getSel_busid1();
                        sel_busid2 = value.getArray().getSel_busid2();
                        sel_busid3 = value.getArray().getSel_busid3();
                        detailAddress.setText(value.getArray().getSel_address());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        prompDialog.dismissImmediately();
                        ToastUtils.showShort("请求数据失败!请检查网络");

                    }
                });

    }

    private void initView() {
    }

    @OnClick({R.id.choose1, R.id.confirm, R.id.choose2, R.id.choose3, R.id.lantie})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirm:
                if (checkParams()) {
                    String bus_id1;
                    if (choose1.getTag() == null) {
                        bus_id1 = sel_busid1;
                    } else {
                        bus_id1 = ((BusinessBean.ArrayBean) choose1.getTag()).getBus_id();
                    }

                    String bus_id2;
                    if (choose2.getTag() == null) {
                        bus_id2 = sel_busid1;
                    } else {
                        bus_id2 = ((BusinessBean.ArrayBean) choose2.getTag()).getBus_id();
                    }

                    String bus_id3;
                    if (choose3.getTag() == null) {
                        bus_id3 = sel_busid3;
                    } else {
                        bus_id3 = ((BusinessBean.ArrayBean) choose3.getTag()).getBus_id();
                    }
                    uploadAddressToServer(bus_id1, bus_id2, bus_id3);
                }

                break;
            case R.id.choose1:
                loadAddress("0", ((TextView) view));
                break;
            case R.id.choose2:

                BusinessBean.ArrayBean tag = (BusinessBean.ArrayBean) choose1.getTag();
                if (tag == null) {
                    if (TextUtils.isEmpty(sel_busid1)) {
                        ToastUtils.showShort("请先选择第一项");
                    } else {
                        loadAddress(sel_busid1, ((TextView) view));
                    }
                } else {
                    String bus_id = tag.getBus_id();
                    loadAddress(bus_id, ((TextView) view));
                }

                break;
            case R.id.choose3:


                BusinessBean.ArrayBean tag2 = (BusinessBean.ArrayBean) choose2.getTag();
                if (tag2 == null) {
                    if (TextUtils.isEmpty(sel_busid2)) {
                        ToastUtils.showShort("请先选择第一项");
                    } else {
                        loadAddress(sel_busid2, ((TextView) view));
                    }
                } else {
                    String bus_id = tag2.getBus_id();
                    loadAddress(bus_id, ((TextView) view));

                }
                break;

            case R.id.lantie:
                Intent intent = new Intent(this, MapActivity.class);
                startActivityForResult(intent, GETLATLNG);
                break;
        }
    }

    /**
     * 长传商户的地址;
     *
     * @param bus_id
     * @param busId
     * @param id
     */
    private void uploadAddressToServer(String bus_id, String busId, String id) {
        prompDialog.showLoading("请等待", false);
        APIServiceManager.getInstance().create(StoreApi.class)
                .saveBusiness(
                        SPUtils.getInstance().getString("userid"),
                        bus_id,
                        busId,
                        id,
                        detailAddress.getText().toString(),
                        resultLatlng.longitude + "",
                        resultLatlng.latitude + "")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<CommonResonseBean>() {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        prompDialog.showSuccess("保存成功", false);
                        ToastUtils.showShort("保存成功");
                        LogUtils.w(value);
                        isSubmit = true;
                        Intent data = new Intent();
                        data.putExtra("status", 1);
                        setResult(RESULT_OK, data);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        prompDialog.showError("保存失败,请重试", false);

                    }
                });


    }

    private boolean checkParams() {

        if (TextUtils.isEmpty(detailAddress.getText().toString())) {
            ToastUtils.showShort("请填写详细的地址");
            return false;
        }
        if (resultLatlng == null) {
            ToastUtils.showShort("请选择经纬度");
            return false;
        }
        if (!"请选择".equals(choose1.getText()) && !"请选择".equals(choose2.getText()) && !"请选择".equals(choose3.getText())) {
            return true;
        } else {
            ToastUtils.showShort("请先选择省市区");
            return false;
        }

    }

    private void loadAddress(String fid, final TextView tv) {
        prompDialog.showLoading("请等待", false);
        APIServiceManager.getInstance().create(StoreApi.class)
                .Business(fid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<BusinessBean>() {
                    @Override
                    public void onSuccess(BusinessBean value) {
                        prompDialog.dismissImmediately();
                        if (value.getArray().size() == 0) {
                            ToastUtils.showShort("服务器返回数据为空" +
                                    "");
                            return;
                        }
                        showPicker(value.getArray(), tv);
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        prompDialog.showError("无法连接网络", false);
                        ToastUtils.showShort("无法连接网络");

                    }
                });
    }


    public void showPicker(final List<BusinessBean.ArrayBean> optionsItems, final TextView view) {


        ArrayList<String> localList = new ArrayList<>();
        for (BusinessBean.ArrayBean optionsItem : optionsItems) {
            String bus_name = optionsItem.getBus_name();
            localList.add(bus_name);

        }
        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                BusinessBean.ArrayBean arrayBean = optionsItems.get(options1);
                view.setText(arrayBean.getBus_name().toString());
                Object lastTag = view.getTag();
                view.setTag(arrayBean);
                BusinessBean.ArrayBean currentTag = arrayBean;

                if (lastTag == null || !((BusinessBean.ArrayBean) lastTag).getBus_id().equals(currentTag.getBus_id())) {
                    if (view == choose1) {
                        //清除子孩子;
                        choose2.setTag(null);
                        choose2.setText("请选择");
                        choose3.setTag(null);
                        choose3.setText("请选择");
                    } else if (view == choose2) {
                        choose3.setTag(null);
                        choose3.setText("请选择");
                    }

                }


                if (view == choose1) {
                    options1Index = options1;
                } else if (view == choose2) {
                    options2Index = options1;
                } else if (view == choose3) {
                    options3Index = options1;
                }


            }
        }).build();
        pvOptions.setPicker(localList);
        pvOptions.show();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GETLATLNG && data != null) {
                resultLatlng = data.getParcelableExtra("latlng");
                String addressDesc = data.getStringExtra("addressDesc");
                if (!TextUtils.isEmpty(addressDesc)) {
                    detailAddress.setText(addressDesc);
                }
            }
        }
    }
}
